package com.sockety2;

import static java.lang.System.out;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Date;
import java.util.Scanner;


public class ThrSocket extends Thread {
	private Socket incoming;
	BehStd stdBeh = new BehStd();
	private Server server;
	
	
	public ThrSocket(Socket socket, Server server){
		this.server = server;
		this.incoming = socket;
	}
	
	@Override
	public void run() {
		if(incoming == null){return;}
		
		try{
            try{
                InputStream inStream = incoming.getInputStream();
                OutputStream outStream = incoming.getOutputStream();
                

                Scanner scan = new Scanner(inStream);
                PrintWriter pw = new PrintWriter(outStream, true);
                

                pw.println(this.getName() + "|" + new Date());
                
                
                while(!Thread.currentThread().isInterrupted()){
                	scan.hasNextLine();
                    String line = scan.nextLine();
                    out.println(line);
                    pw.println("ECHO: " + line);
                    if(line.trim().equals("-shd")){server.kill();};
                    
                    Object result = stdBeh.todo(line.trim());
                    
                    if(result != null){
                    	if( result instanceof String){
                    		String strResult = (String)result;
                    		pw.println();
                    		pw.print(strResult);
                    	}
                    }
                    
                }
            }
            finally{
                incoming.close();
            }
        }
        catch(IOException e ){
            e.printStackTrace();
            Thread.currentThread().interrupt();
        }
	}
}
